// services/cabinet/cabinet.js
const { backendApiUrl } = require('../../utils/config');
import { apiRequest, apiUpload } from '../_utils/apiRequest';
const userModel = require('../../model/user');

/**
 * 获取用户的柜主申请信息
 * @param {string} userId - 用户 ID
 * @returns {Promise} - 返回柜主申请信息的 Promise
 */
export const getCabinetApplicationByUser = () => {
  return apiRequest({
    url: `${backendApiUrl}/application/cabinetowner/byuser/me`,
    method: 'GET',
  });
};

/**
 * 提交撤回申请
 * @param {string} applicationId - 柜主申请 ID
 * @returns {Promise} - 返回撤回申请的结果
 */
export const applyRecall = (applicationId) => {
  return apiRequest({
    url: `${backendApiUrl}/application/recall/${applicationId}`,
    method: 'PUT',
  });
};

/**
 * 确认收货并上传凭证图片
 * @param {number} applicationId - 申请的 ID
 * @param {string[]} imageList - 图片文件路径数组
 * @returns {Promise<object>} - 返回更新结果
 */
async function confirmReceipt(applicationId, imageList) {
  try {
    // 创建所有图片的上传 Promise
    const uploadPromises = imageList.map(filePath => uploadProofImage(applicationId, filePath));

    // 等待所有图片上传完成
    await Promise.all(uploadPromises);

    // 调用 updateApplication 更新状态为 DELIVERED
    await updateApplication({
      id: applicationId,
      status: 'DELIVERED',
    });

    return { message: '确认收货成功' };
  } catch (error) {
    throw error;
  }
}

/**
 * 上传单张凭证图片
 * @param {number} applicationId - 申请的 ID
 * @param {string} filePath - 图片文件路径
 * @returns {Promise<object>} - 返回上传结果
 */
const uploadProofImage = async (applicationId, filePath) => {
  try {
    const res = await apiUpload({
      url: `${backendApiUrl}/application/me/updateProof`, // 确保路径包含 /api/v1
      filePath,
      name: 'proofImages', // 务必与后端 multer 配置一致
      formData: {
        id: applicationId,
      },
    });
    console.log('上传成功：', res);
    return res; // 返回服务器的响应数据
  } catch (error) {
    console.error('上传失败：', error);
    wx.showToast({
      title: error.message || '上传失败',
      icon: 'none',
    });
    // 错误处理，根据需要决定是否抛出
    throw error // 将错误抛出，方便上层处理
  }
};

/**
 * 更新申请的其他字段（现有函数）
 * @param {object} data - 更新数据
 * @returns {Promise<object>} - 返回更新结果
 */
async function updateApplication(data) {
  return apiRequest({
    url: `${backendApiUrl}/application/me/update`,
    method: 'PUT',
    data,
  });
}

async function applicationCabinetOwner(data) {
  return apiRequest({
    url: `${backendApiUrl}/application/cabinetowner`,
    method: 'POST',
    data,
  });
}

async function generateAndUpdateQrcode(userId, applicationId) {
  try {

    const response = await apiRequest({
      url: `${backendApiUrl}/wechat/generateQrcode`,
      method: "POST",
      data: { userId, applicationId },
    });

    const { fileUrl, base64 } = response;

    // 更新本地 user model 数据
    const userData = userModel.getUserData();
    if (userData?.info.cabinetOwnerApplication) {
      userData.info.cabinetOwnerApplication.qrCode = base64;
      userData.info.cabinetOwnerApplication.qrCodeUrl = fileUrl;
      userModel.setUserData({ token:userData.token, userInfo: userData.info });
    }

    // 更新当前页面的 qrcodeUrl，用于显示
    return {fileUrl:fileUrl, base64};
  } catch (error) {
    console.error("生成或更新二维码失败:", error);
    wx.showToast({
      title: "二维码生成失败，请联系客服",
      icon: "none",
    });
  }
}

module.exports = {
  getCabinetApplicationByUser,
  applyRecall,
  updateApplication,
  confirmReceipt,
  applicationCabinetOwner,
  generateAndUpdateQrcode,
};
